
var prefix = ctx +"module/citizen";
$(function() {
    load();
});
function load(){
    layui.use(['form','laydate','table'], function() {
        var form = layui.form , laydate = layui.laydate,
            table = layui.table, element = layui.element;//载入table模块

        laydate.render({
            elem: '#begin_date',
            isInitValue: false,
        });
        laydate.render({
            elem: '#end_date',
            isInitValue: false,
        });
        var user_type  = parseInt($('#user_type').val());

        var searchParams = {};
        searchParams['search_like_keyword']=$('#keyword').val();
        searchParams['search_eq_townId']=$('#townId').val();
        searchParams['search_eq_villageId']=$('#villageId').val();
        if($('#begin_date').val() != "" && $('#end_date').val() != ""){
            searchParams['begin_date'] = $('#begin_date').val() + " 00:00:00";
            searchParams['end_date'] = $('#end_date').val() + " 23:59:59";
        }

        form.on('select(townId)', function (data) {
            console.log('townId',data.value);
            getVillages(data.value,form)
        });

        var cols = [];
        if(user_type < 3){
            cols = [[
                { type:'checkbox',fixed : 'left' },
                { field : 'townName',  title : '乡镇名称', align : 'center', },
                { field : 'villageName',  title : '村居名称', align : 'center', },
                { field : 'holderName',  title : '房主姓名', align : 'center', },
                // { field : 'holderPhone',  title : '房主电话', align : 'center', },
                { field : 'roomNo',  title : '房屋编号', align : 'center', },
                { title : '取暖方式', align : 'center',
                    templet: function (item) {
                        return (loadCategory('heating_mode')[item.heatingMode] ? loadCategory('heating_mode')[item.heatingMode] : '');
                    }
                },
                { title : '户类别', align : 'center',
                    templet: function (item) {
                        return (loadCategory('room_type')[item.roomType] ? loadCategory('room_type')[item.roomType] : '');
                    }
                },
                { field : 'starLevel',  title : '风险等级', align : 'center',
                    templet: function (item) {
                        var ss = "";
                        for (var i = 0;i< item.starLevel;i++){
                            ss += "<i class='layui-icon layui-icon-rate-solid' style='color:red;'></i>";
                        }
                        return  ss;
                    },
                },
                { title : '二维码', align : 'center', width:200,
                    templet: function (item) {
                        return "<a href=\"javascript:void(0);\" imgurl=\""+item.qrCode+"\" class=\"grid-column-qrcode text-muted\">" +
                            "           <i class=\"fa fa-qrcode\"></i>" +
                            "       </a>"+
                            "       &nbsp;&nbsp;<a href='"+prefix + "/download/"+item.id + "' " +
                            " download='room_qr_"+item.townName +"_"+ item.villageName+"_"+item.roomNo+".jpg'>" +
                            "<i class=\"fa fa-download\"></i>"+item.townName + item.villageName +"No."+item.roomNo+"</a>";
                    },
                },
                // { field : 'managerName',  title : '包保人员', align : 'center', },
                // { field : 'managerPhone',  title : '包保人员电话', align : 'center', },
                { title: '操作', width: 200, templet: '#currentTableBar', align: "center"}
            ]];
        }else{
            cols = [[
                { type:'checkbox',fixed : 'left' },
                { field : 'townName',  title : '乡镇名称', align : 'center', },
                { field : 'villageName',  title : '村居名称', align : 'center', },
                { field : 'holderName',  title : '房主姓名', align : 'center', },
                // { field : 'holderPhone',  title : '房主电话', align : 'center', },
                { field : 'roomNo',  title : '房屋编号', align : 'center', },
                { title : '取暖方式', align : 'center',
                    templet: function (item) {
                        return (loadCategory('heating_mode')[item.heatingMode] ? loadCategory('heating_mode')[item.heatingMode] : '');
                    }
                },
                { title : '户类别', align : 'center',
                    templet: function (item) {
                        return (loadCategory('room_type')[item.roomType] ? loadCategory('room_type')[item.roomType] : '');
                    }
                },
                { field : 'starLevel',  title : '风险等级', align : 'center',
                    templet: function (item) {
                        var ss = "";
                        for (var i = 0;i< item.starLevel;i++){
                            ss += "<i class='layui-icon layui-icon-rate-solid' style='color:red;'></i>";
                        }
                        return  ss;
                    },
                },
                { title: '操作', width: 200, templet: '#currentTableBar', align: "center"}
            ]];
        }

        //初始化table
        table.render({
            elem: '#exampleTable',//承载数据的table Id
            url: prefix + "/list",//请求数据连接
            toolbar: '#toolbarDemo',
            cellMinWidth: 80,//全局定义所有常规单元格的最小宽度（默认：60）
            even: true,//是否开启隔行变色
            loading:true,//是否显示加载条
            // height: 'full-75',
            where :{
                searchParams:searchParams,
                sorts:{"id":"desc"}
            },
            limits: [10, 50, 100, 200, 300,500,700,1000],
            //page: true,//是否分页
            page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: [ 'prev', 'page', 'next', 'skip', 'count','limit'] //自定义分页布局
            },
            defaultToolbar: false,
            cols: cols,
            id: 'currentTableId',//表格Id
            done: function(res, curr, count){
                // $('.layui-table-fixed-r').removeClass('layui-hide');
                $(".grid-column-qrcode").each(function() {
                    $(this).click(function() {
                        previewImg(this);
                    })
                });
            } //解决最右侧列不能固定的问题
        });
        /**
         * 操作栏tool  监听事件
         */
        table.on('tool(currentTableFilter)', function (obj) {
            if (obj.event === 'edit') {  // 监听添加操作
                console.log('obj',obj.data.id)
                edit(obj.data.id);
            } else if (obj.event === 'delete') {  // 监听删除操作
                console.log('obj',obj.data.id)
                remove(obj.data.id);
            } else if (obj.event === 'qrcode') {  // 监听删除操作
                resetQrcode(obj.data.id);
            }
        });
        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            //执行搜索重载
            reLoad();
            return false;
        });

        /**
         * 操作栏tool  监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                add();
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                layer.alert(JSON.stringify(data));
            } else if(obj.event === 'batchQrcode'){
                var checkStatus = table.checkStatus('currentTableId'),
                    data = checkStatus.data;
                checkedArr = data;
                var ids = [];
                for(var index in checkedArr){
                    ids.push(checkedArr[index].id);
                }
                if (ids.length < 1) {
                    layer.msg('无选中项');
                    return false;
                }
                batchQrcode(ids);
            } else if(obj.event === 'batchDownloadQrcode'){
                getCitizenQrCode()
            } else if(obj.event === 'upload_user'){
                batchAdd();
            } else if(obj.event === 'bathResetQrCode'){
                bathResetQrCode();
            } else if(obj.event === 'export'){
                exportExcel();
            }
        });
    });
}

function getCitizenQrCode() {
    var townId = $("#townId").val();
    var begin_date = $("#begin_date").val();
    var end_date = $("#end_date").val();

    var villageId = $("#villageId").val();

    if(townId == '' || townId == undefined){
        layer.msg('请选择乡镇下载');
    }else{
        window.location.href = ctx + 'module/citizen/downloadQRCode?townId=' + townId + '&villageId='  + villageId
            + "&beginDate=" +begin_date + "&endDate=" + end_date;
    }
}


function exportExcel(){

    layer.confirm('确定要导出本乡镇的居民信息吗？数量多导出时间会很长【导出时请耐心等待，不要刷新界面！】', {
        btn : [ '确定', '取消' ]
    }, function() {
        var townId = $("#townId").val();
        var villageId = $("#villageId").val();

        console.log('townId',townId)
        console.log('villageId',villageId)

        if(townId == undefined || townId == 0){
            layer.msg("请选择乡镇导出");
            return;
        }
        // if(villageId == undefined || villageId == 0){
        //     layer.msg("请选择村庄导出");
        //     return;
        // }
        window.location.href = ctx + 'module/citizen/exportExcel?townId=' + townId +'&villageId=' +  villageId;
    })
}


function batchAdd() {
    var index = layer.open({
        type : 2,
        title : '批量增加',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '320px' ],
        content : ctx + 'module/citizen/goBatchAdd' // iframe的url
    });
}

function getVillages(townId,form) {
    $.ajax({
        url : prefix + "/villages",
        type : "post",
        data:{
            townId:townId
        },
        success : function(r) {
            console.log('r',r)
            if (r.code==0) {
                console.log("villages",r.villages);

                var villages = r.villages;
                if (villages.length > 0) {
                    $('#villageId').empty();
                    $('#villageId').append(new Option('请选择村居', ''));
                    for (var i = 0; i < villages.length; i++) {
                        $('#villageId').append(new Option(villages[i].townName, villages[i].id));
                    }
                } else {
                    $('#villageId').empty();
                    $('#villageId').append(new Option('暂无村居', ''));
                }
                form.render("select");
            }
        }
    });
}

function resetQrcode(id){
    $.ajax({
        url : prefix + "/resetQrCode",
        type : "post",
        data : {
            'id' : id
        },
        success : function(r) {
            if (r.code==0) {
                layer.msg(r.msg);
                reLoad();
            }else{
                layer.msg(r.msg);
            }
        }
    });
}


function bathResetQrCode(){
    var townId = $("#townId").val();
    if(townId === undefined || townId === ''){
        layer.msg('请选择乡镇');
    }else{
        $.ajax({
            url : prefix + "/updateQrCode/" + townId,
            type : "post",
            data : { },
            success : function(r) {
                if (r.code==0) {
                    layer.msg(r.msg);
                    reLoad();
                }else{
                    layer.msg(r.msg);
                }
            }
        });
    }
}



function previewImg(obj) {
    console.log('obj',obj)
    var img = new Image();
    img.src = $(obj).attr("imgurl");
    console.log('img',$(obj).attr("imgurl"));
    var imgHtml = "<img src='" + img.src + "' width='400' height='400' style='margin: 25px 25px'/>";
    //弹出层
    layer.open({
        type: 1,
        // shade: true,
        shadeClose : true, // 点击遮罩关闭层
        title: false, //不显示标题
        area:[ '450px', '450px' ],
        content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
        cancel: function () {

        }
    });
}

function batchQrcode(ids) {
    $.ajax({
        type : 'POST',
        data : {
            "ids" : ids
        },
        url : prefix + '/batchQrCode',
        success : function(r) {
            if (r.code === 0) {
                layer.msg(r.msg);
                reLoad();
            } else {
                layer.msg(r.msg);
            }
        }
    });
}

function reLoad() {
    var searchParams = {};
    searchParams['search_like_keyword']=$('#keyword').val();
    searchParams['search_eq_townId']=$('#townId').val();
    searchParams['search_eq_villageId']=$('#villageId').val();
    if($('#begin_date').val() !== "" && $('#end_date').val() !== ""){
        searchParams['begin_date'] = $('#begin_date').val() + " 00:00:00";
        searchParams['end_date'] = $('#end_date').val() + " 23:59:59";
    }
    layui.use(['table'], function() {
        var table = layui.table;//载入table模块
        table.reload('currentTableId', {
            page: {curr: 1}
            , where: {
                searchParams: searchParams
            }
        }, 'data');
    });
}

function add() {
	var index = layer.open({
        type : 2,
        title : '增加',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '600px', '580px' ],
        content : prefix + '/add' // iframe的url
    });
	// layer.full(index);
}

function edit(id) {
	var index = layer.open({
        type : 2,
        title : '编辑',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '600px', '580px' ],
        content : prefix + '/edit/' + id // iframe的url
    });
	// layer.full(index);
}

function remove(id) {
    layer.confirm('确定要删除选中的记录？', {
        btn : [ '确定', '取消' ]
    }, function() {
        $.ajax({
            url : prefix+"/remove",
            type : "post",
            data : {
                'id' : id
            },
            success : function(r) {
                if (r.code==0) {
                    layer.msg(r.msg);
                    reLoad();
                }else{
                    layer.msg(r.msg);
                }
            }
        });
    })
}


